package com.cheea.associationBss.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.cheea.associationBss.interceptor.LoginInterceptor;
import com.cheea.associationBss.model.Article;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;

@Before (LoginInterceptor.class)
public class ArticleController extends Controller {
	public void index(){
		Integer id = getParaToInt();
		if(id!=null){
			setAttr("article", Article.dao.findById(id));
		}
		render("article.jsp");
	}
	public void recruitment(){
		Integer id = getParaToInt();
		if(id!=null){
			setAttr("article", Article.dao.findById(id));
		}
		render("recruitment.jsp");
	}
	public void save(){
		Article article = getModel(Article.class);
		String title = getPara("title").trim();
		String content = getPara("content").trim();
		Integer id = getParaToInt("id");
		article.set("title", title);
		article.set("content", content);
		//判断是招募
		if(getParaToInt("recruitmentNum")!=null){
			article.set("recruitmentNum", getParaToInt("recruitmentNum"));
			article.set("flag", 1);
			article.set("belong", getSessionAttr("uid"));
		}
		boolean r = false;
		try{
			if(id!=null){
				article.set("id", id);
				//是博文的原作者才可以编辑
				Integer originCreateUserId=Article.dao.findById(id).get("createUserId");
				if(getSessionAttr("uid")!=null&&originCreateUserId.toString().equals(getSessionAttr("uid").toString())){
					r=article.update();
				}else{
					setAttr("msg", "您不是原文的作者，不能编辑,现在为您跳转到首页");
					setAttr("redirectPage", "/associationBss");
				}
			}else{
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				article.set("createTime",df.format(new Date()));
				article.set("createUserId", getSessionAttr("uid"));
				article.set("createUserName", getSessionAttr("uname"));
				r = article.save();
			}
			if(r){
				setAttr("msg", "恭喜哈，文章发布成功了,现在为您跳转到首页");
				setAttr("redirectPage", "/associationBss");
			}else{
				setAttr("msg", "糟糕，文章发布失败了,现在为您跳转到首页");
				setAttr("redirectPage", "/associationBss");
			}
		}catch(Exception e){
			setAttr("msg", "糟糕，文章发布失败了,现在为您跳转到首页");
			setAttr("redirectPage", "/associationBss");
		}
		render("/view/common/msg.jsp");
	}
	@ClearInterceptor
	public void viewzm(){
		Article article = Article.dao.findById(getParaToInt());
		setAttr("article", article);
		if(getSessionAttr("uid")!=null){
			setAttr("isAuthor", article.get("createUserId").toString().equals(getSessionAttr("uid").toString()));
		}
		render("viewzm.jsp");
	}
	
	@ClearInterceptor
	public void view(){
		Article article = Article.dao.findById(getParaToInt());
		setAttr("article", article);
		if(getSessionAttr("uid")!=null){
			setAttr("isAuthor", article.get("createUserId").toString().equals(getSessionAttr("uid").toString()));
		}
		render("view.jsp");
	}
}
